package com.w.wx.service.impls;

import com.w.wx.mapper.CommentsInfoMapper;
import com.w.wx.mapper.CommentsReplyMapper;
import com.w.wx.mapper.GoodsMapper;
import com.w.wx.mapper.LikedMapper;
import com.w.wx.domain.CommentsInfo;
import com.w.wx.domain.Liked;
import com.w.wx.service.LikedService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;

@Service
@Slf4j

public class LikedServiceImpl implements LikedService {

    @Autowired
    private RedisServiceImpl redisService;
    @Autowired
    private LikedMapper likedMapper;
    @Autowired
    private CommentsInfoMapper commentsInfoMapper;
    @Autowired
    private CommentsReplyMapper commentsReplyMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 将缓存中点赞记录持久化到数据库
     */
    @Override
    @Transactional
    public void transLikedFromRedisToDB() {
        List<Liked> likeds = redisService.getLikedDataFromRedis();

        for (Liked like : likeds) {
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            //首先判断之前是否有
            Liked liked = likedMapper.selectByObjIdAndOpenid(like.getObjId(),like.getUserOpenid(),like.getType());
            if(liked==null ){
                //没有则新增
                like.setCreateTime(timestamp);
                likedMapper.insert(like);
            }else{
                //有则更新
                 likedMapper.updateByPrimaryKey(liked.getLikeId(),like.getLikeStatus(),timestamp);
            }
        }
    }

    /**
     * 将点赞数量持久化到数据库
     */
    @Override
    @Transactional
    public void transLikedCountFromRedisToDB() {
        Cursor<Map.Entry<Object, Object>> cursor = redisService.getLikedCountFromRedis();
        while (cursor.hasNext()){
            Map.Entry<Object, Object> map = cursor.next();
            String key = (String)map.getKey();
            //分离出objId和type
            String[] split = key.split("::");
            int type =Integer.parseInt(split[1]);
            int objId = Integer.parseInt(split[0]);
            int likeNum = (Integer) map.getValue();
            if ( type == 1){
                //为主评论
                commentsInfoMapper.updateByPrimaryKey(objId,likeNum);

            }else if(type == 2){
                //为子评论
                commentsReplyMapper.updateByPrimaryKey(objId,likeNum);
            }else{
                //为物品
                goodsMapper.updateGoodsLikeSum(objId,likeNum);
            }
        }
    }

    @Override
    public List<Map<String,Object>> selectLikedInfoByType(Integer type) {
        return likedMapper.selectLikedInfoByType(type);
    }
}
